<template>
  <div>
    <el-button type="primary" @click="showDialog">新增员工</el-button>

    <el-table :data="employees" style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="position" label="职位"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="edit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form">
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model.number="form.age"></el-input>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="form.position"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      employees: [],
      dialogVisible: false,
      form: { id: null, name: '', age: null, position: '' }
    }
  },
  computed: {
    dialogTitle() {
      return this.form.id ? '编辑员工' : '新增员工'
    }
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      const res = await axios.get('http://localhost:8080/api/employees');
      this.employees = res.data;
    },
    showDialog() {
      this.form = { id: null, name: '', age: null, position: '' };
      this.dialogVisible = true;
    },
    edit(row) {
      this.form = { ...row };
      this.dialogVisible = true;
    },
    async remove(id) {
      await this.$confirm('确认删除吗？', '提示');
      await axios.delete(`/api/employees/${id}`);
      this.fetchData();
    },
    async submit() {
      const url = this.form.id 
        ? `/api/employees/${this.form.id}`
        : '/api/employees';
      
      await (this.form.id 
        ? axios.put(url, this.form)
        : axios.post(url, this.form));
      
      this.dialogVisible = false;
      this.fetchData();
    }
  }
}
</script>